# import random
# import requests
# from util.myjwt import myjwt
# from util.sms_code import send_message
# import json
# from flask import Blueprint, jsonify, json, redirect, make_response
# from db import db
# import datetime
# from flask import current_app as app, request
# from util.myredis import r
# # from education.education.util.comm import get_ali_object
# import time
# user_blue = Blueprint('user', __name__)
# # u_blue = Blueprint("ublue", "__name__")
# # 发送短信接口
# @user_blue.route("/sendsms", methods=["GET"])
# def sendsms():
#     # 获取参数mobil、uuid、imagecode
#     data = json.loads(request.data)
#     print(">>>", data)
#     mobile = data["mobile"]
#     uuid = data["uuid"]
#     print(">>>>", uuid)
#     imagecode = data["imagecode"]
#     if not all([mobile, imagecode, uuid]):
#         return jsonify({"code": 20010, "msg": "参数不完整"})
#     # 验证图片验证码
#     code = r.str_get(uuid)
#     # 通过uuid从redis取出来和传递过来的参数在对比，全部转为小写
#     if code:
#         if imagecode.lower() != code.decode().lower():
#             return jsonify({"code": 20011, "msg": "图片验证码错误"})
#         # 清除redis中的图片验证码
#         r.del_key(uuid)
#     else:
#         return jsonify({"code": 20013, "msg": "没有获取到图片验证码"})
#     # 1分钟内只能发送一次
#     v = r.str_get(mobile)
#     if v:
#         return jsonify({"code": 20014, "msg": "一分钟内只能发送一次"})
#     # 如果成功调用写入redis队列
#     r.list_push("smsmobile", mobile)
#     # 短信接口qps每秒请求100
#     return jsonify({"code": 200, "msg": "ok"})
#
# # 手机验证码
# @user_blue.route("/send")
# def send():
#     while True:
#         # 查看队列长度，如果没值不处理
#         for i in range(2):
#             len = r.list_len("smsmobile")
#             if len > 0:
#                 value = r.list_pop("smsmobile")
#                 mobile = value.decode()
#                 # 如果长度大于1
#                 code = random.randint(1000, 9999)
#                 print(">>>>>>>>>>")
#                 print(code)
#                 print(">>>>>>>>>>")
#                 res = send_message(mobile, code)
#                 print(">>>>>>>>>>>>>>>>>>>>>>>>>>>", res)
#                 # 判断是否成功，成功写入redis
#                 r.str_setex(mobile, code, 60)
#         time.sleep(1)
#         return jsonify({"code": 200, "msg": "获取验证码成功", "sms": code})
#
# # 登录接口
# @user_blue.route("/login", methods=["POST"])
# def login():
#     # 获取手机号和验证码
#     data = json.loads(request.data)
#     mobile = data["mobile"]
#     code = data["code"]
#     print(mobile)
#     # 获取验证码进行判断
#     codemes = r.str_get(mobile)
#     if codemes:
#         if str(codemes.decode()) != str(code):
#             return jsonify({"code": 10030, "msg": "验证码错误"})
#         # 清除验证码
#         r.del_key(mobile)
#         # 通过手机号查询数据库
#         sql = "select * from user where mobile='%s'" % (mobile)
#         user = db.findone(sql)
#         # 返回用户信息
#         if user:
#             # 调用jwt、encode生成token
#             data = {"data": {"userid": user["id"], "mobile": [
#                 "mobile"], "exptime": int(time.time())}}
#             token = myjwt.jwt_encode(data)
#             return jsonify({"code": 200, "msg": "登陆成功", "token": token, "userid": user["id"]})
#         return jsonify({"code": 201, "msg": "没有该用户"})
import jwt
from flask import Blueprint,jsonify,current_app,send_file
from flask_restful import Api,Resource,reqparse
from util.myredis import r
from util.sms_code import send_message
from application.models.users.user import UsersModel,db
from captcha.image import ImageCaptcha
login_bp = Blueprint("login_bp",__name__)
api = Api(login_bp)
import random
import time
class ImgView(Resource):
    def get(self):
        img = ImageCaptcha()
        code = random.randint(1000,9999)
        code1 = str(code)
        img_png = img.generate(code1)
        return send_file(img_png,mimetype="png")
api.add_resource(ImgView,"/img")

class SmsView(Resource):
    def get(self,mobile):
        code = str(random.randint(1000,9999))
        send_message(mobile,code)
        r.str_setex(mobile,60,code)
        time.sleep(5)
        return jsonify({"code":200,"msg":"ok"})
api.add_resource(SmsView,"/sms/<mobile>")

class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("nikename")
        req.add_argument("mobile")
        args = req.parse_args()
        if not all([args["nikename"],args["mobile"]]):
            return jsonify({
                "code":400,
                "msg":"数据不完整"
            })
        user = UsersModel.query.filter(UsersModel.nikename == args["nikename"]).first()
        if not user:
            u = UsersModel(nikename=args["nikename"],mobile=args["mobile"])
            db.session.add(u)
            db.session.commit()
            return jsonify({"code":200,"msg":"注册成功"})
        if user.password != args["password"]:
            return jsonify({
                "code":400,
                "msg":"信息错误"
            })
        key = current_app.config.get("SECRET_KEY")
        token = jwt.encode({
            "user_id":user.id,
            "exp":int(time.time()) + 30
        },key,algorithm="HS256")
        return jsonify({"code":200,"msg":"登录成功","token":token})
api.add_resource(LoginView,"/login")